package com.hmall.search.listener;

import com.alibaba.fastjson.JSON;
import com.hmall.common.Constant.SearchConstant;
import com.hmall.common.dto.Item;
import com.hmall.search.pojo.ItemDOC;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
public class AddListener {
    @Autowired
    RestHighLevelClient client;
    
    @RabbitListener(queues = "lazy.queue")
    public void process1(List<Item> itemList) throws IOException {
        add(itemList);
    }
    @RabbitListener(queues = "lazy.queue")
    public void process2(List<Item> itemList) throws IOException {
        add(itemList);
    }
    @RabbitListener(queues = "lazy.queue")
    public void process3(List<Item> itemList) throws IOException {
        add(itemList);
    }
    
    private void add(List<Item> itemList) throws IOException {
        //创建批量请求
        BulkRequest bulkRequest = new BulkRequest();
        //获取全部的hotel对象集合
        for (Item item : itemList) {
            //将hotel对象转化为DOC格式的HotelDoc对象
            ItemDOC itemDOC = new ItemDOC(item);
            //将HotelDoc对象转换为json字符串
            String jsonHotelDoc = JSON.toJSONString(itemDOC);
            //创建request对象
            IndexRequest indexRequest = new IndexRequest(SearchConstant.INDEX_NAME).id(itemDOC.getId().toString());
            //设置添加文档的字段和json数据
            indexRequest.source(jsonHotelDoc, XContentType.JSON);
            //将请求批量添加至bulkRequest内
            bulkRequest.add(indexRequest);
        }
        //发送请求
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
    }
}
